<template>
  <el-dialog
    v-model="visible"
    title="选择变量"
    width="600px"
    @close="handleClose"
  >
    <el-alert
      type="info"
      :closable="false"
      style="margin-bottom: 16px"
    >
      选择前置节点的输出字段，支持 JSONPath 语法
    </el-alert>

    <el-tabs v-model="activeTab">
      <el-tab-pane label="选择节点" name="select">
        <div v-if="predecessorNodes.length === 0">
          <el-empty description="没有可引用的前置节点" />
        </div>

        <el-radio-group v-else v-model="selectedNodeId" style="width: 100%">
          <el-space direction="vertical" style="width: 100%" :size="12">
            <el-radio
              v-for="node in predecessorNodes"
              :key="node.id"
              :label="node.id"
              border
              style="width: 100%; margin: 0"
            >
              <div class="node-info">
                <div class="node-label">{{ node.label }}</div>
                <el-tag size="small">{{ node.type }}</el-tag>
              </div>
            </el-radio>
          </el-space>
        </el-radio-group>

        <div v-if="selectedNodeId" style="margin-top: 16px">
          <el-divider content-position="left">输出数据预览</el-divider>
          <el-alert type="info" :closable="false" style="margin-bottom: 8px">
            <template #title>
              <span style="font-size: 13px;">
                以下是该节点的典型输出结构（仅供参考）
              </span>
            </template>
          </el-alert>
          <pre class="output-preview">{{ outputPreview }}</pre>
        </div>
      </el-tab-pane>

      <el-tab-pane label="输入路径" name="path">
        <el-form label-width="100px">
          <el-form-item label="节点ID">
            <el-input v-model="selectedNodeId" placeholder="如: nodeA" />
          </el-form-item>

          <el-form-item label="JSONPath">
            <el-input
              v-model="jsonPath"
              placeholder="如: versionInfo.outputs[0].obsUrl"
            />
            <div class="field-hint">
              <el-text type="info" size="small">
                支持嵌套访问和数组索引，如: field.subfield[0].value
              </el-text>
            </div>
          </el-form-item>

          <el-form-item label="完整引用">
            <el-input :value="generatedVariable" disabled>
              <template #append>
                <el-button @click="copyToClipboard">复制</el-button>
              </template>
            </el-input>
          </el-form-item>
        </el-form>

        <el-divider />

        <div class="examples">
          <div class="example-title">常用示例：</div>
          <el-tag
            v-for="example in examples"
            :key="example.path"
            class="example-tag"
            @click="applyExample(example)"
          >
            {{ example.label }}
          </el-tag>
        </div>

        <!-- 环境变量快捷选择 -->
        <el-divider v-if="environmentVariables.length > 0" />

        <div v-if="environmentVariables.length > 0" class="environment-variables">
          <div class="env-title">
            <el-icon><Setting /></el-icon>
            环境变量快捷选择：
          </div>
          <div class="env-hint">
            <el-text type="info" size="small">
              点击环境变量名称可快速填充到 JSONPath 输入框
            </el-text>
          </div>
          <div class="env-list">
            <div
              v-for="envVar in environmentVariables"
              :key="envVar.path"
              class="env-item"
              @click="applyEnvironmentVariable(envVar)"
            >
              <div class="env-label">
                <el-tag type="success" size="small">{{ envVar.label }}</el-tag>
              </div>
              <div class="env-path">
                <el-text type="info" size="small">{{ envVar.path }}</el-text>
              </div>
              <div class="env-value">
                <el-text type="primary" size="small" truncated>
                  当前值: {{ envVar.value }}
                </el-text>
              </div>
            </div>
          </div>
        </div>
      </el-tab-pane>
    </el-tabs>

    <template #footer>
      <el-button @click="handleClose">取消</el-button>
      <el-button type="primary" @click="handleConfirm">插入</el-button>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, computed, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { Setting } from '@element-plus/icons-vue'
import { parseYaml } from '@/utils/yamlTemplateParser'

const props = defineProps({
  modelValue: Boolean,
  predecessorNodes: {
    type: Array,
    default: () => []
  }
})

const emit = defineEmits(['update:modelValue', 'confirm'])

const visible = computed({
  get: () => props.modelValue,
  set: (val) => emit('update:modelValue', val)
})

const activeTab = ref('select')
const selectedNodeId = ref('')
const jsonPath = ref('')

// 根据节点类型提供输出结构预览
const outputPreview = computed(() => {
  if (!selectedNodeId.value) return ''

  const node = props.predecessorNodes.find(n => n.id === selectedNodeId.value)
  if (!node) return ''

  // 根据节点类型返回典型输出结构
  if (node.type === 'create_experiment') {
    return JSON.stringify({
      versionId: "abc123",
      romaStatusCode: "10",
      versionInfo: {
        name: "experiment-001",
        status: "completed",
        outputs: [
          {
            obsUrl: "obs://bucket/path/to/output",
            type: "result",
            size: 1024000
          },
          {
            obsUrl: "obs://bucket/path/to/checkpoint",
            type: "checkpoint",
            size: 512000
          }
        ],
        metrics: {
          accuracy: 0.95,
          loss: 0.05
        }
      }
    }, null, 2)
  } else if (node.type === 'download_data') {
    return JSON.stringify({
      filePath: "/data/output",
      fileSize: 1024000,
      status: "下载完成",
      downloadTime: "2025-11-05T12:00:00Z"
    }, null, 2)
  } else if (node.type === 'data_processing') {
    return JSON.stringify({
      status: "处理完成",
      recordCount: 10000,
      outputPath: "/data/processed",
      metrics: {
        processingTime: 120,
        memoryUsed: 2048
      }
    }, null, 2)
  }

  return '{}'
})

// 生成的变量引用
const generatedVariable = computed(() => {
  if (!selectedNodeId.value) return ''
  if (!jsonPath.value) return `{{${selectedNodeId.value}.<路径>}}`
  return `{{${selectedNodeId.value}.${jsonPath.value}}}`
})

// 常用示例
const examples = [
  { label: '实验名称', path: 'versionInfo.name' },
  { label: '训练输出数据', path: 'versionInfo.outputs[0].obsUrl' },
]

const applyExample = (example) => {
  jsonPath.value = example.path
}

// 获取当前选中节点的环境变量列表（扁平化）
const environmentVariables = computed(() => {
  if (!selectedNodeId.value) return []

  const node = props.predecessorNodes.find(n => n.id === selectedNodeId.value)
  if (!node || !node.config) return []

  // 从 experimentConfig YAML 字符串中解析环境变量
  let envs = null

  try {
    if (node.config.experimentConfig) {
      // 如果有 experimentConfig，从 YAML 中解析
      const yamlData = parseYaml(node.config.experimentConfig)
      console.log('解析的 YAML 数据:', yamlData)
      envs = yamlData?.config?.environments
      console.log('解析的环境变量:', envs)
    }
  } catch (error) {
    console.error('解析 experimentConfig YAML 失败:', error)
    return []
  }

  if (!envs || typeof envs !== 'object') return []

  // 扁平化环境变量，JSONPath 为 config.environments.{key}
  return Object.keys(envs).map(key => ({
    label: key,
    path: `versionInfo.environments.${key}`,
    value: envs[key]
  }))
})

// 应用环境变量到 JSONPath
const applyEnvironmentVariable = (envVar) => {
  jsonPath.value = envVar.path
}

const copyToClipboard = () => {
  if (navigator.clipboard && navigator.clipboard.writeText) {
    navigator.clipboard.writeText(generatedVariable.value)
    ElMessage.success('已复制到剪贴板')
  } else {
    // 降级方案：使用 textarea 复制
    const textarea = document.createElement('textarea')
    textarea.value = generatedVariable.value
    textarea.style.position = 'fixed'
    textarea.style.opacity = '0'
    document.body.appendChild(textarea)
    textarea.select()
    try {
      document.execCommand('copy')
      ElMessage.success('已复制到剪贴板')
    } catch (err) {
      ElMessage.error('复制失败，请手动复制')
    }
    document.body.removeChild(textarea)
  }
}

const handleConfirm = () => {
  if (!generatedVariable.value || generatedVariable.value.includes('<路径>')) {
    ElMessage.warning('请输入完整的变量路径')
    return
  }

  emit('confirm', generatedVariable.value)
  handleClose()
}

const handleClose = () => {
  visible.value = false
  selectedNodeId.value = ''
  jsonPath.value = ''
  activeTab.value = 'select'
}

// 监听选中节点变化，自动切换到路径输入标签
watch(selectedNodeId, (newVal) => {
  if (newVal && activeTab.value === 'select') {
    activeTab.value = 'path'
  }
})
</script>

<style lang="scss" scoped>
.node-info {
  display: flex;
  align-items: center;
  justify-content: space-between;
  width: 100%;

  .node-label {
    font-weight: 500;
  }
}

.output-preview {
  background-color: #f5f7fa;
  padding: 12px;
  border-radius: 4px;
  font-size: 12px;
  font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', 'Consolas', 'source-code-pro', monospace;
  max-height: 300px;
  overflow: auto;
  margin: 0;
}

.field-hint {
  margin-top: 4px;
}

.examples {
  .example-title {
    font-size: 14px;
    margin-bottom: 8px;
    color: #606266;
    font-weight: 500;
  }

  .example-tag {
    margin-right: 8px;
    margin-bottom: 8px;
    cursor: pointer;
    transition: all 0.2s;

    &:hover {
      opacity: 0.8;
      transform: translateY(-1px);
    }
  }
}

.environment-variables {
  .env-title {
    font-size: 14px;
    margin-bottom: 8px;
    color: #606266;
    font-weight: 500;
    display: flex;
    align-items: center;
    gap: 6px;
  }

  .env-hint {
    margin-bottom: 12px;
  }

  .env-list {
    display: flex;
    flex-direction: column;
    gap: 8px;
    max-height: 300px;
    overflow-y: auto;
  }

  .env-item {
    padding: 12px;
    background-color: #f5f7fa;
    border-radius: 6px;
    border: 1px solid #e4e7ed;
    cursor: pointer;
    transition: all 0.2s;

    &:hover {
      background-color: #e8f4ff;
      border-color: #409eff;
      transform: translateX(2px);
    }

    .env-label {
      margin-bottom: 6px;
    }

    .env-path {
      margin-bottom: 4px;
      font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', 'Consolas', 'source-code-pro', monospace;
    }

    .env-value {
      color: #909399;
    }
  }
}
</style>
